<template>
  <div class="shipment ">
    <Aside />
    <!-- 主体部分 -->
    <main>
      <Nav />
      <div class="top">
        <History />
      </div>
      <div class="content">
        <div class="center">
          <span class="name ">Summary</span>
          <span class="name_right"></span>
          <table class="left">
            <div class="header">
              <span class="title">List</span>
              <span @click="renovate" class="renovate">Renovate</span>
              <el-select @change="Changedate" v-model="date" class="m-1" placeholder="Select Time">
                <el-option label="Past 30 days" :value="sendTime_30" />
                <el-option label="Past 90 days" :value="sendTime_90" />
                <el-option :label="renderLastYear" :value="renderLastYear" />
                <el-option :label="renderYearBeforeLast" :value="renderYearBeforeLast" />
                <div class="Date_box">
                  <el-date-picker @change="changeFromDate" format="DD/MM/YYYY" class="Date" v-model="FromDate" type="date"
                    placeholder="FromDate" :size="size" />
                  <el-date-picker @change="changeToDate" format="DD/MM/YYYY" class="Date" v-model="ToDate" type="date"
                    placeholder="ToDate" :size="size" />
                </div>
              </el-select>
              <el-select @change="changeStatus" v-model="freightStatus" class="m-2" placeholder="Select Status">
                <el-option v-for="(item, index) in Status" :key="index" :label="item.render" :value="item.code" />
              </el-select>
              <el-select filterable remote :remote-show-suffix="'我'" @change="changeCountry" :remote-method="SelectChange"
                :loading="loading" v-model="SelectCountry" class="m-3" placeholder="Enter Country">
                <el-option v-for="(item, index) in country" :key="index" :label="item.name" :value="item.country_id" />
              </el-select>
              <el-link type="primary" @click="exportClick()">Download</el-link>
            </div>
            <div class="myList" ref="export">
              <p class="title">
                <span>NO.</span>
                <span>Sales</span>
                <span>Date</span>
                <span>Way</span>
                <span>Fee</span>
                <span>Doc.</span>
                <span>AWB</span>
                <span>CNT</span>
                <span>Status</span>
                <span>Action</span>
              </p>
              <Transition-group name="ivy" tag="ul">
                <li :class="{ 'content': '会发着呆', 'active': activeIndex == item.Shiptask_id }"
                  v-for="(item, index) in list" :key="index" @click="getDetails(item.Shiptask_id)">
                  <span :title="item.Shiptask_name">{{ item.Shiptask_name }}</span>
                  <span :title="item.nickname">{{ item.nickname }}</span>
                  <span :title="item.create_time">{{ item.create_time }}</span>
                  <span :title="item.shipping_way">{{ item.shipping_way }}</span>
                  <span :title="item.Shipping_cost">{{ item.Shipping_cost }}</span>
                  <span :title="item.OddNumbers">{{ item.OddNumbers }}</span>
                  <span :title="item.TransferNo">{{ item.TransferNo }}</span>
                  <span :title="item.country">{{ item.country }}</span>
                  <span :title="item.freight_status">{{ item.freight_status }}</span>
                  <span><span title="Eidt" @click="edit(item)">Edit</span><span title="SeeLOG"
                      @click="look(item)">SeeLOG</span></span>
                </li>
              </Transition-group>
              <el-pagination v-model:current-page="pageNum" :page-size="pageSize" :disabled="disabled"
                :background="background" layout="total, prev, pager, next" :total="total"
                @current-change="handleCurrentChange" />
              <!-- 编辑弹窗 -->
              <el-dialog center v-model="editDialog" title="Edit" :close-on-press-escape="false"
                :close-on-click-modal="false" :show-close="false">
                <div class="editContent">
                  <p>
                    <span>Way</span>
                    <el-select v-model="editWay" class="editWay" placeholder="Select">
                      <el-option v-for="item in waySelect" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                  </p>
                  <p><span>Fee</span><input v-model="editFee" class="input" type="text" placeholder="Please enter"></p>
                  <p><span>Doc</span><input v-model="editDoc" class="input" type="text" placeholder="Please enter"></p>
                  <p><span>AWB</span><input v-model="editAWB" class="input" type="text" placeholder="Please enter"></p>
                </div>
                <div class="editButton">
                  <button @click="cancelEdit">取消</button>
                  <button :class="{ 'isDisabled': isDisabled }" :disabled="isDisabled" @click="editSave">保存</button>
                </div>
              </el-dialog>
              <!-- 查看物流弹窗 -->
              <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :show-close="false"
                class="logistics" v-model="viewLogistics" title="View logistics">
                <div class="logisticsTitle">
                  <span>{{ courierName }}</span>
                  <span>{{ queryState }}</span>
                </div>
                <div v-if="LogisticsStatus.length == 0" class="empty">暂无数据</div>
                <div v-else class="logisticsBox">
                  <el-timeline>
                    <el-timeline-item ref="timeline" type="primary " :hollow="true" placement="top" :center="true"
                      v-for="(item, index) in LogisticsStatus" :key="index" :timestamp="item.time">
                      {{ item.context }}
                    </el-timeline-item>
                  </el-timeline>
                </div>
                <div class="logisticsButton">
                  <button @click="close">关闭</button><button @click="query">查询</button>
                </div>
              </el-dialog>
            </div>
          </table>
          <div class="right">
            <div class="header">
              <p><span>PI</span><span>MODEL</span><span>QTY</span></p>
              <ul class="content_box" v-infinite-scroll="loadTransport" :infinite-scroll-immediate="false">
                <li class="content_li" v-for="(item, index) in transportationDetails" :key="index">
                  <span :title="item.PI_name">{{ item.PI_name }}</span>
                  <span :title="item.model">{{ item.model }}</span>
                  <span :title="item.Qtynumber">{{ item.Qtynumber }}</span>
                </li>
              </ul>
            </div>
            <div class="middle">
              <div class="top_nav">
                <span @click="packAdd = true">Add</span>
                <span @click="packEditFn">Edit</span>
                <span @click="packDelete">Delete</span>
              </div>
              <p><span>CARTON</span><span>SIZE</span><span>NET(Kg)</span><span>Gross(Kg)</span></p>
              <ul class="content_box" v-infinite-scroll="loadPack" :infinite-scroll-immediate="false">
                <li :class="{ 'content_li': '然后忘记你，接着紧紧闭上眼', 'activePack': packActiveIndex == item.id }"
                  @click="getPackId(item, index)" v-for="(item, index) in packingList" :key="index">
                  <span :title="`${index + 1} of ${packTotal}`"> {{ index + 1 }} of {{ packTotal }} </span>
                  <span :title="`${item.long}x${item.wide}x${item.high}`">{{ item.long }}x{{ item.wide }}x{{ item.high
                  }}</span>
                  <span :title="item.netWeight">{{ item.netWeight }}</span>
                  <span :title="item.grossWeight">{{ item.grossWeight }}</span>
                </li>
              </ul>
            </div>
            <!-- 添加打包弹窗 -->
            <el-dialog v-model="packAdd" title="Add" class="packAddDialog">
              <div class="top">
                <input v-model="packNum" class="num" type="text" placeholder="Please enter the packing quantity">
                <span @click="AddPackNum">Define</span>
              </div>
              <ul class="content_pack">
                <li v-for="(item, index) in packArry">
                  <span class="left_pack">{{ index + 1 }} of {{ packArry.length }}</span>
                  <div class="right_pack">
                    <div>
                      <span>length</span>
                      <input v-model="item.long" type="text">
                    </div>
                    <div>
                      <span>wide</span>
                      <input v-model="item.wide" type="text">
                    </div>
                    <div>
                      <span>height</span>
                      <input v-model="item.high" type="text">
                    </div>
                    <div>
                      <span>netWeight</span>
                      <input v-model="item.netWeight" type="text">
                    </div>
                    <div>
                      <span>grossWeight</span>
                      <input v-model="item.grossWeight" type="text">
                    </div>
                  </div>
                </li>
              </ul>
              <div class="footer_btn">
                <button :disabled="cannotClick" :class="{ 'Save_btn': '想着哪一天，会有人代替', 'cannotClick': cannotClick }"
                  @click="packadd">Save</button>
                <button class="Cancel_btn" @click="packCancel">Cancel</button>
              </div>
            </el-dialog>
            <!-- 编辑打包弹窗 -->
            <el-dialog v-model="packEdit" title="Edit" class="packEditDialog">
              <ul class="content_pack">
                <li>
                  <div>
                    <span>length</span>
                    <input v-model="packEditObj.long" type="text">
                  </div>
                  <div>
                    <span>wide</span>
                    <input v-model="packEditObj.wide" type="text">
                  </div>
                  <div>
                    <span>height</span>
                    <input v-model="packEditObj.high" type="text">
                  </div>
                  <div>
                    <span>netWeight</span>
                    <input v-model="packEditObj.netWeight" type="text">
                  </div>
                  <div>
                    <span>grossWeight</span>
                    <input v-model="packEditObj.grossWeight" type="text">
                  </div>
                </li>
              </ul>
              <div class="footer_btn">
                <span class="Save_btn" @click="packEditSave">Save</span>
                <span class="Cancel_btn" @click="packEdit = false">Cancel</span>
              </div>
            </el-dialog>
            <div class="bottom">
              <div class="top_nav">
                <span @click="upLoadImg">Upload</span>
                <span @click="share">Share</span>
                <span @click="deleteImg">Delete</span>
              </div>
              <div class="img_box">
                <transition-group name="hp" tag="ul">
                  <li :class="{ 'imgActive': item.isShow }" v-for="(item, index) in renderImg" :key="index"
                    @click="SelcetImg(item)">
                    <img :src="item.file_path" alt="">
                  </li>
                  <div @click="addImg" class="SelectPicture">
                    <el-icon>
                      <Plus />
                    </el-icon>
                    <input ref="imgLoad" type="file" style="display: none;">
                  </div>
                </transition-group>
              </div>
              <!-- 图片分享弹窗 -->
              <el-dialog class="shareDialog" v-model="shareDialog" title="File sharing" width="30%">
                <div class="content">
                  <div class="shareDialog_left">
                    <div class="cipherSwitch">
                      <el-switch v-model="cipher" />
                      <span>通过密码分享</span>
                    </div>
                    <input v-show="cipher" v-model="password" type="text" placeholder="password">
                  </div>
                  <div class="shareDialog_right">
                    <div class="shareDialog_right_footer">
                      <span>到期时间: </span>
                      <span>{{ ExpirationTime }}</span>
                    </div>
                    <el-select size="small" @change="SelectExpirationTime" v-model="Mytime" class="m-2"
                      placeholder="Select">
                      <el-option label="1天过期" :value="oneDays" />
                      <el-option label="30天过期" :value="oneMonth" />
                      <el-option label="90天过期" :value="trimester" />
                      <el-option label="半年过期" :value="halfYear" />
                      <el-option label="一年过期" :value="oneYear" />
                    </el-select>
                  </div>
                </div>
                <div class="footer_button">
                  <button @click="off">取消</button>
                  <button @click="sendInterlinkageDialog">生成链接</button>
                </div>
              </el-dialog>
              <!-- 生成链接弹窗 -->
              <el-dialog class="interlinkageDialog" v-model="interlinkageDialog" title="File sharing" width="30%">
                <p>
                  <span>链接：</span>
                  <span>{{ imgUrl }}</span>
                </p>
                <p v-show="cipher">
                  <span>提取码：</span>
                  <span>{{ password }}</span>
                </p>
                <div class="footer_button">
                  <button @click="Cancel" class="cancel">取消</button>
                  <button @click="copyUrl" class="copy">复制并关闭</button>
                </div>
              </el-dialog>
            </div>
          </div>
        </div>
        <!-- 聊天区域 -->
        <div class="IM">
          <!-- 右边 -->
          <div class="right">
            <div class="consult flex aic">
              <img
                src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.dtstatic.com%2Fuploads%2Fblog%2F202103%2F31%2F20210331160001_9a852.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.dtstatic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673675691&t=dcdcdb2297f6a373d82936bf1fb2a5e2"
                alt="" />
              <img
                src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.dtstatic.com%2Fuploads%2Fblog%2F202103%2F31%2F20210331160001_9a852.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.dtstatic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673675691&t=dcdcdb2297f6a373d82936bf1fb2a5e2"
                alt="" />
              <img
                src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.dtstatic.com%2Fuploads%2Fblog%2F202103%2F31%2F20210331160001_9a852.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.dtstatic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673675691&t=dcdcdb2297f6a373d82936bf1fb2a5e2"
                alt="" />
            </div>

            <div class="info pl-10 pr-10 f14">
              <div class="flex mt-20">
                <img
                  src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.dtstatic.com%2Fuploads%2Fblog%2F202103%2F31%2F20210331160001_9a852.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.dtstatic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673675691&t=dcdcdb2297f6a373d82936bf1fb2a5e2"
                  alt="" />
                <p class="what ml-10 mt-10">芊妙机器人</p>
              </div>
              <div class="flex mt-20 jc-e">
                <p class="what mr-10 mt-10">芊妙机器人</p>
                <img
                  src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.dtstatic.com%2Fuploads%2Fblog%2F202103%2F31%2F20210331160001_9a852.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.dtstatic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673675691&t=dcdcdb2297f6a373d82936bf1fb2a5e2"
                  alt="" />
              </div>
              <div class="flex mt-20">
                <img
                  src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.dtstatic.com%2Fuploads%2Fblog%2F202103%2F31%2F20210331160001_9a852.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.dtstatic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673675691&t=dcdcdb2297f6a373d82936bf1fb2a5e2"
                  alt="" />
                <p class="what ml-10 mt-10">芊妙机器人</p>
              </div>
            </div>

            <div class="chat pl-10 pr-10 flex fdc">
              <el-input v-model="chat" :autosize="{ minRows: 5, maxRows: 4 }" type="textarea"
                placeholder="please enter" />
              <el-button class="mt-10 flex jc-e" type="primary" round>dispatch</el-button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, onUpdated, TransitionGroup, watch } from "vue";
import Nav from "../components/Nav.vue";
import Aside from "../components/Aside.vue";
import * as api from '../../api2/index';
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useDemoStore } from '../../pinia/index';
import * as XLSX from 'xlsx';
const token = useDemoStore().token
const url = localStorage.getItem('url')
const url0 = 'http://s7-1500.cn/www/html/product/image/CRM_Product_Image.php?path='

//时间线
const LogisticsStatus = ref([])
//改变物流时间线的样式
const timeline = ref()
const renderColor = () => {
  let myTime = setTimeout(() => {
    if (LogisticsStatus.value.length != 0 && viewLogistics.value) {
      console.log(timeline.value[0])
      console.log(timeline.value[0]._.vnode.el.childNodes[3].childNodes[0])
      timeline.value[0]._.vnode.el.childNodes[1].style.borderColor = '#ff3c41'
      timeline.value[0]._.vnode.el.childNodes[3].childNodes[0].style.color = '#ff3c41'
      timeline.value[0]._.vnode.el.childNodes[3].childNodes[1].style.color = '#ff3c41'
    }
  }, 500)
  if (!viewLogistics.value) {
    clearTimeout(myTime)
  }
}

//查询条件
const date = ref();
const FromDate = ref()
const ToDate = ref()
//处理选择的时间
const handleSelectTime = (value, name) => {
  let Year = value.getFullYear()
  let Month = value.getMonth() + 1
  let day = value.getDate()
  Month = Month < 10 ? '0' + Month : Month
  day = day < 10 ? '0' + day : day
  date.value = Year
  name.value = `${Year}-${Month}-${day}`
  if (name == FromDate.value) {
    sendTime.value[0] = `${name.value} 00:00:00`
  } else {
    sendTime.value[1] = `${name.value} 23:59:59`
  }
  if (sendTime.value.length == 2) {
    getIndex(sendTime.value, freightStatus.value, SelectCountry.value, pageNum.value, pageSize.value)
  }
}
const changeFromDate = (val) => {
  handleSelectTime(val, FromDate.value)
}
const changeToDate = (val) => {
  handleSelectTime(val, ToDate.value)
}
const freightStatus = ref()
const Status = ref([])
const country = ref([])
const loading = ref(false)
const SelectCountry = ref()
//获取时间
const renderLastYear = ref()
const sendTime = ref([])
const sendTime_30 = ref()
const sendTime_90 = ref()
const renderYearBeforeLast = ref()
const getTime = () => {
  let time = new Date();
  let Year = time.getFullYear()
  renderLastYear.value = Year - 1;
  renderYearBeforeLast.value = Year - 2;
  sendTime_30.value = handleTime(30, 'before')
  sendTime_90.value = handleTime(90, 'before')
  oneDays.value = handleTime(1, 'after')
  oneMonth.value = handleTime(30, 'after')
  trimester.value = handleTime(90, 'after')
  halfYear.value = handleTime(182, 'after')
  oneYear.value = handleTime(365, 'after')
  Mytime.value = oneDays.value
  ExpirationTime.value = oneDays.value
  timeStamp.value = Date.parse(new Date(ExpirationTime.value)) / 1000
}
//处理过期时间
const handleTime = (time, isTrue) => {
  let nowDate = Date.now()
  if (isTrue == 'before') {
    let nowtime = new Date(nowDate - (24 * 60 * 60 * 1000 * time))
    let Year = nowtime.getFullYear()
    let mth = nowtime.getMonth() + 1
    let day = nowtime.getDate()
    mth = mth < 10 ? '0' + mth : mth
    day = day < 10 ? '0' + day : day
    return `${Year}-${mth}-${day}`
  } else if (isTrue == 'after') {
    let nowtime = new Date(nowDate + (24 * 60 * 60 * 1000 * time))
    let Year = nowtime.getFullYear()
    let mth = nowtime.getMonth() + 1
    let day = nowtime.getDate()
    let hour = nowtime.getHours();
    let minute = nowtime.getMinutes();
    let ssecond = nowtime.getSeconds();
    mth = mth < 10 ? '0' + mth : mth
    day = day < 10 ? '0' + day : day
    hour = hour < 10 ? '0' + hour : hour
    minute = minute < 10 ? '0' + minute : minute
    ssecond = ssecond < 10 ? '0' + ssecond : ssecond
    return `${Year}-${mth}-${day} ${hour}:${minute}:${ssecond}`
  } else {
    return null
  }

}
//获取国家
const SelectChange = (val) => {
  console.log(val)
  if (val) {
    loading.value = true
    api.$getCountryList({ token: token, country: val }).then(res => {
      console.log(res)
      loading.value = false
      country.value = res.data
    }).catch(err => {
      console.log(err)
    })
  }
}
// 首页加载
const list = ref([])
const total = ref()
const pageSize = ref(13)
const pageNum = ref(1)
const getIndex = (date, Status, country, pageNo, pageSize) => {
  api.$index({ token: token, date: date, freightStatus: Status, country: country, pageNo: pageNo, pageSize: pageSize }).then(res => {
    console.log(res)
    list.value = res.data.data
    total.value = res.data.total
    if (res.data.data.length != 0) {
      activeIndex.value = res.data.data[0].Shiptask_id
    }
    getShipTaskInfo(shiptaskPageNo.value, shiptaskPageSize.value)//首次加载详情
    packList(packPageNo.value, packPageSize.value)
    getImage(activeIndex.value)
  }).catch(err => {
    console.log(err)
  })
}
//首页列表分页
const handleCurrentChange = (val) => {
  list.value = []//清空列表
  transportationDetails.value = []//清空详情
  packingList.value = []//清空打包列表
  copyImg.value = []//清空图片列表
  pageNum.value = val
  getIndex(sendTime.value, freightStatus.value, SelectCountry.value, pageNum.value, pageSize.value)
}
//获取货运状态
const getFreightStatus = () => {
  api.$getFreightStatus({ token: token }).then(res => {
    console.log(res)
    Status.value = res.data
  }).catch(err => {
    console.log(err)
  })
}
//刷新列表
const renovate = () => {
  transportationDetails.value = []//清空详情
  packingList.value = []//清空打包列表
  copyImg.value = []//清空图片列表
  freightStatus.value = ''//清空状态
  sendTime.value = []//清空之前的时间
  list.value = []//清空列表
  SelectCountry.value = ''//清空国家
  pageNum.value = 1
  packPageNo.value = 1
  shiptaskPageNo.value = 1
  getIndex(sendTime.value, freightStatus.value, SelectCountry.value, pageNum.value, pageSize.value)
}
//更改时间后的列表
const Changedate = (val) => {
  transportationDetails.value = []//清空详情
  packingList.value = []//清空打包列表
  copyImg.value = []//清空图片列表
  freightStatus.value = ''//清空状态
  sendTime.value = []//清空之前的时间
  list.value = []//清空列表
  SelectCountry.value = ''//清空国家
  pageNum.value = 1 //页数重置为1
  let startTime
  let endTime
  if (val.toString().length == 4) {
    startTime = `${val}-01-01  00:00:00`
    endTime = `${val}-12-31  23:59:59`
  } else if (val.toString().length == 10) {
    startTime = `${val} 00:00:00`
    endTime = `${val} 23:59:59`

  }
  sendTime.value[0] = startTime
  sendTime.value[1] = endTime
  getIndex(sendTime.value, freightStatus.value, SelectCountry.value, pageNum.value, pageSize.value)
}
//更改状态后的列表
const changeStatus = (val) => {
  transportationDetails.value = []//清空详情
  packingList.value = []//清空打包列表
  copyImg.value = []//清空图片列表
  sendTime.value = []//清空时间
  SelectCountry.value = ''//清空国家
  date.value = ''//清空日期
  list.value = []//清空列表
  pageNum.value = 1 //页数重置为1
  getIndex(sendTime.value, freightStatus.value, SelectCountry.value, pageNum.value, pageSize.value)
}
//更改国家后的列表
const changeCountry = (val) => {
  transportationDetails.value = []//清空详情
  packingList.value = []//清空打包列表
  copyImg.value = []//清空图片列表
  sendTime.value = []//清空时间
  date.value = ''//清空日期
  freightStatus.value = ''//清空状态
  list.value = []//清空列表
  pageNum.value = 1 //页数重置为1
  getIndex(sendTime.value, freightStatus.value, SelectCountry.value, pageNum.value, pageSize.value)
}

//获取列表详情
const transportationDetails = ref([])
const activeIndex = ref(0)
const shiptaskPageNo = ref(1)
const shiptaskPageSize = ref(7)
const getShipTaskInfo = (pageNo, pageSize) => {
  api.$getShipTaskInfo({ token: token, shiptaskid: activeIndex.value, pageNo: pageNo, pageSize: pageSize }).then(res => {
    console.log(res)
    res.data.data.forEach(item => {
      transportationDetails.value.push(item)
    });
  }).catch(err => {
    console.log(err)
  })
}
//获取运输列表的信息
const getDetails = (id) => {
  transportationDetails.value = []//清空详情
  packingList.value = []//清空打包列表
  copyImg.value = []//清空图片列表
  activeIndex.value = id;
  packPageNo.value = 1
  shiptaskPageNo.value = 1
  getShipTaskInfo(shiptaskPageNo.value, shiptaskPageSize.value)
  packList(packPageNo.value, packPageSize.value)
  getImage(activeIndex.value)
}
//列表详情动态加载
const loadTransport = () => {
  console.log('s')
  shiptaskPageNo.value = ++shiptaskPageNo.value
  getShipTaskInfo(shiptaskPageNo.value, shiptaskPageSize.value)
}

//获取列表打包
const packActiveIndex = ref()
const packPageNo = ref(1)
const packPageSize = ref(4)
const packingList = ref([])
const packTotal = ref()
const packList = (pageNo, pageSize, change) => {
  api.$packList({ token: token, shiptaskid: activeIndex.value, pageNo: pageNo, pageSize: pageSize }).then(res => {
    console.log(res)
    packTotal.value = res.data.total
    if (change) { //如果是删除或者编辑则替换掉原本的数据
      res.data.data.forEach((item, index) => {
        packingList.value[RangeChangeIndex.value * packPageSize.value + index] = item
      })
    } else {
      res.data.data.forEach(item => {
        packingList.value.push(item)
      })
    }

    packActiveIndex.value = packingList.value[0]?.id//初始化默认打包Id
    if (packingList.value[0]) {
      let packEditStr = JSON.stringify(packingList.value[0])
      packEditObj = JSON.parse(packEditStr)//默认选择打包
    } else {
      packEditObj = null
    }
  }).catch(err => {
    console.log(err)
  })
}

//打包列表动态加载
const loadPack = () => {
  packPageNo.value = ++packPageNo.value
  packList(packPageNo.value, packPageSize.value)
}

//添加打包弹窗
const packAdd = ref(false)
const packNum = ref()//输入打包的数量
const packArry = ref([])
const packObj = reactive({
  long: '',
  wide: '',
  high: '',
  netWeight: '',
  grossWeight: ''
})
const AddPackNum = () => {
  cannotClick.value = false
  packArry.value.length = packNum.value
  for (let i = 0; i < packArry.value.length; i++) {
    packArry.value[i] = JSON.parse(JSON.stringify(packObj))
  }
  packNum.value = ''
}
//如果packArry没有生成，则添加打包按钮不能点击
const cannotClick = ref(true)
//发送添加的打包
let count = ref(1)
const packadd = () => {
  packingList.value = []
  let reg = /^\d*(\.\d{1,20})?$/;
  for (let i = 0; i < packArry.value.length; i++) {
    if (packArry.value[i].long == '' || !reg.test(packArry.value[i].long)) { ElMessage({ type: "error", message: 'Length cannot be empty and must be an integer or decimal!' }); count.value = 2; return }
    if (packArry.value[i].wide == '' || !reg.test(packArry.value[i].wide)) { ElMessage({ type: "error", message: 'Width cannot be empty and can be integer or decimal!' }); count.value = 2; return }
    if (packArry.value[i].high == '' || !reg.test(packArry.value[i].high)) { ElMessage({ type: "error", message: 'High cannot be empty and must be an integer or decimal!' }); count.value = 2; return }
    if (packArry.value[i].grossWeight == '' || !reg.test(packArry.value[i].grossWeight)) { ElMessage({ type: "error", message: 'Gross weight cannot be empty and must be an integer or decimal!' }); count.value = 2; return }
    if (packArry.value[i].netWeight == '' || !reg.test(packArry.value[i].netWeight)) { ElMessage({ type: "error", message: 'Net weight cannot be empty and must be an integer or decimal!' }); count.value = 2; return }
    count.value = 1
  }
  if (count.value == 1) {
    api.$packadd({ token: token, shiptaskid: activeIndex.value, pack: packArry.value }).then(res => {
      console.log(res)
      packAdd.value = false
      cannotClick.value = true
      packArry.value = []
      packPageNo.value = count.value
      packList(packPageNo.value, packPageSize.value,)
      ElMessage({
        type: 'success',
        message: 'Successfully added'
      })
    }).catch(err => {
      console.log(err)
      ElMessage({
        type: 'error',
        message: 'Add failed'
      })
    })
  }
}
//取消打包
const packCancel = () => {
  packAdd.value = false
  ElMessage({
    type: 'error',
    message: 'Canceled'
  })
  packArry.value = []
  cannotClick.value = true
}
//编辑打包
let packEditObj = reactive({})
const packEdit = ref(false)
const packArrIndex = ref(0)
const getPackId = (item, index) => {
  console.log(index)
  packArrIndex.value = index //拿到编辑的索引
  packActiveIndex.value = item.id
  packEditObj = JSON.parse(JSON.stringify(item))
}
const packEditFn = () => {
  if (packEditObj == null) {
    ElMessage({
      type: "error",
      message: "No packaging!"
    })
    return
  }
  packEdit.value = true
}
//保存打包编辑
const findIndex = () => {//计算操作的数据位于数组中第几页
  RangeChangeIndex.value = packArrIndex.value / packPageSize.value
  if (RangeChangeIndex.value < 1) {
    RangeChangeIndex.value = 0
  } else {
    RangeChangeIndex.value = Math.floor(RangeChangeIndex.value)
  }
  packPageNo.value = RangeChangeIndex.value + 1 //修改的第几页，就拿第几页的数据
}
const RangeChangeIndex = ref()
const packEditSave = () => {
  packEdit.value = false
  api.$packedit({
    token: token, packid: packActiveIndex.value, long: packEditObj.long, wide: packEditObj.wide,
    high: packEditObj.high, netWeight: packEditObj.netWeight, grossWeight: packEditObj.grossWeight
  }).then(res => {
    //拿到编辑的索引，找到它在数组中是第几页的范围
    findIndex()
    packList(packPageNo.value, packPageSize.value, "让我不再")//重新加载数据
    ElMessage({
      type: 'success',
      message: 'Edit succeeded'
    })
  }).catch(err => {
    console.log(err)
    ElMessage({
      type: 'error',
      message: 'Edit failed'
    })
  })
}

//删除打包
const packDelete = () => {
  if (packActiveIndex.value == undefined) {
    ElMessage({
      type: "error",
      message: 'No packaging!'
    })
    return
  }
  api.$packdel({ token: token, packid: packActiveIndex.value }).then(res => {
    console.log(res)
    findIndex()
    packingList.value.splice(packArrIndex.value, 1)
    packList(packPageNo.value, packPageSize.value, "想念你~")//重新加载数据
    ElMessage({
      type: 'success',
      message: 'Delete succeeded'
    })
  }).catch(err => {
    console.log(err)
    ElMessage({
      type: 'error',
      message: 'Delete failed'
    })
  })
}

//添加图片
const imgLoad = ref()
const copyImg = ref([])
const sendImg = ref([])
const renderImg = ref([])
const addImg = () => {
  imgLoad.value.click()
  imgLoad.value.addEventListener('change', () => {
    copyImg.value.push(imgLoad.value.files[0])
    sendImg.value = copyImg.value.filter(item => item != undefined)
    renderImg.value = sendImg.value.map(item => {
      let blob = new Blob([item])
      let url = URL.createObjectURL(blob)
      let obj = {
        file_path: url
      }
      return obj
    })
    imgLoad.value.value = ''
  })
}
//上传图片
const upLoadImg = () => {
  copyImg.value = []//清空图片列表
  if (sendImg.value.length != 0) {
    api.$transportImageUpload({ token: token, taskid: activeIndex.value, files: sendImg.value }).then(res => {
      console.log(res)
      ElMessage({
        type: 'success',
        message: 'Upload succeeded'
      })
      getImage(activeIndex.value)
      sendImg.value = []//清空发送的图片
    }).catch(err => {
      console.log(err)
      ElMessage({
        type: 'error',
        message: 'Upload failed'
      })
    })
  } else {
    ElMessage({
      type: "error",
      message: "Please select a picture"
    })
  }

}
//获取图片
const getImg = ref()
const getImage = (id) => {
  api.$getImage({ token: token, taskid: id }).then(res => {
    console.log(res)
    getImg.value = JSON.parse(JSON.stringify(res.data))
    let copyImg = [];
    renderImg.value = [];
    if (res.data != null) {
      copyImg = res.data.map(item => {
        if (item.external == 1) {
          item.file_path = item.file_path.replaceAll('\\', '/');
          item.file_path = url + "/TransportImage/" + item.file_path;
        } else {
          item.file_path = item.file_path.replaceAll('.', '&ext=');
          item.file_path = url0 + item.file_path
        }
        return item
      })
    } else {
      return copyImg = []
    }
    copyImg.forEach(item => {
      let obj = { 'isShow': false }
      renderImg.value.push(Object.assign(item, obj))
    })
  }).catch(err => {
    console.log(err)
  })
}

//分享图片
const shareDialog = ref(false)
const cipher = ref(false)
const password = ref()
const Mytime = ref()
const oneDays = ref()
const oneMonth = ref()
const trimester = ref()
const halfYear = ref()
const oneYear = ref()
const ExpirationTime = ref()
const share = () => {
  if (renderImg.value.length == 0) {
    ElMessage({
      type: "error",
      message: "No picture!"
    })
    return
  }
  shareDialog.value = true

}
//选择到期时间
const timeStamp = ref()
const SelectExpirationTime = (val) => {
  console.log(val)
  ExpirationTime.value = val
  timeStamp.value = Date.parse(new Date(ExpirationTime.value)) / 1000
}
//取消
const off = () => {
  shareDialog.value = false
  password.value = ''
  cipher.value = false
}
//生成链接
const getSharingLinkFn = () => {
  let address = window.location.host
  interlinkageDialog.value = true
  shareDialog.value = false
  api.$getSharingLink({ token: token, address: address, files: getImg.value, pwd: password.value, expiration_time: timeStamp.value }).then(res => {
    console.log(res)
    imgUrl.value = res.data.share
  }).catch(err => {
    console.log(err)
  })
}
const imgUrl = ref()
const interlinkageDialog = ref(false)
//生成链接弹窗
const sendInterlinkageDialog = () => {
  let reg = /^[A-Za-z0-9]+$/
  if (password.value) {
    if (password.value.length != 6) { ElMessage({ type: 'error', message: 'Password length must be 6 digits' }); return }
    if (!reg.test(password.value)) { ElMessage({ type: 'error', message: 'The password must consist of letters and numbers' }); return }
    getSharingLinkFn()
  } else {
    getSharingLinkFn()
  }

}

//取消分享
const Cancel = () => {
  interlinkageDialog.value = false
  imgUrl.value = ''
  password.value = ''
  cipher.value = false
}
//复制链接
const copyUrl = () => {
  let input = document.createElement('input')
  input.value = imgUrl.value
  document.body.appendChild(input)
  input.select()
  document.execCommand('copy')
  document.body.removeChild(input)
  interlinkageDialog.value = false
  localStorage.setItem('imgUrl', imgUrl.value)
  password.value = ''
  cipher.value = false
}

//删除图片
const deleteImgArr = ref([])
const SelcetImg = (val) => {
  val.isShow = !val.isShow
}

const delIamges = () => {//删除图片接口
  api.$delIamges({ token: token, imageid: deleteImgArr.value }).then(res => {
    getImage(activeIndex.value)
    deleteImgArr.value = []
  }).catch(err => {
    console.log(err)
  })
}
const deleteImg = () => {
  renderImg.value.forEach(item => {
    if (item.isShow) deleteImgArr.value.push(item.files_id)
  })
  if (deleteImgArr.value.length == 0) {
    ElMessage({
      type: 'error',
      message: "Please select a picture!"
    })
  } else {
    ElMessageBox.confirm('Are you sure you want to delete it?', 'warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: "Cancel",
        type: 'warning',
        center: true,
      }).then(() => {
        delIamges()
        ElMessage({
          type: "success",
          message: 'Delete succeeded!',
        })
      }).catch(() => {
        ElMessage({
          type: 'error',
          message: "Canceled"
        })
      })
  }
}

//表格导出
const exportExcel = (filename, data) => {
  let exc = XLSX.utils.book_new();
  let exc_data = XLSX.utils.aoa_to_sheet(data);
  XLSX.utils.book_append_sheet(exc, exc_data, filename)
  XLSX.writeFile(exc, `${filename}.xlsx`)
}
const exportClick = () => {
  let data = [['NO', 'Sales', 'Date', 'Way', 'Fee', 'Doc', 'AWB', 'CNT', 'Status']]
  data.length = list.value.length + 1
  for (let i = 1; i < data.length; i++) {
    data[i] = [];
    data[i].length = data[0][0].length;
    data[i][0] = list.value[i - 1].Shiptask_name
    data[i][1] = list.value[i - 1].nickname
    data[i][2] = list.value[i - 1].create_time
    data[i][3] = list.value[i - 1].shipping_way
    data[i][4] = list.value[i - 1].Shipping_cost
    data[i][5] = list.value[i - 1].OddNumbers
    data[i][6] = list.value[i - 1].TransferNo
    data[i][7] = list.value[i - 1].country
    data[i][8] = list.value[i - 1].freight_status
  }
  ElMessageBox.confirm('Are you sure you want to download', 'warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: "Cancel",
      type: 'warning',
      center: true,
    }).then(() => {
      ElMessage({
        type: "success",
        message: 'Downloading',
      })
      exportExcel('运输任务', data)
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: "Canceled"
      })
    })
};

//查看
const item = ref()
const queryState = ref()
const courierName = ref()
const viewLogistics = ref(false)
const look = (val) => {
  item.value = val
  LogisticsStatus.value = []
  console.log(val)
  viewLogistics.value = true
  api.$GetLogisticsNode({ token: token, OddNumbers: val.OddNumbers, TransferNo: val.TransferNo, shiptaskid: val.Shiptask_id, orderid: val.order_id, isquery: 0 }).then(res => {
    console.log(res.data)
    queryState.value = res.data.Msg
    courierName.value = res.data.expTextName
    if (res.data.Data != null) {
      for (let i = 0; i < res.data.Data.length; i++) {
        LogisticsStatus.value.push(res.data.Data[i])
      }
    } else {
      LogisticsStatus.value = []
    }
  }).catch(err => {
    console.log(err)
  })
}

//查询
const query = () => {
  LogisticsStatus.value = []
  console.log(item.value)
  api.$GetLogisticsNode({ token: token, OddNumbers: item.value.OddNumbers, TransferNo: item.value.TransferNo, shiptaskid: item.value.Shiptask_id, orderid: item.value.order_id, isquery: 1 }).then(res => {
    console.log(res)
    LogisticsStatus.value = res.data.Data
    renderColor()
  }).catch(err => {
    console.log(err)
  })
}

//关闭物流弹窗
const close = () => {
  viewLogistics.value = false
  list.value = []//清空列表
  transportationDetails.value = []//清空详情
  packingList.value = []//清空打包列表
  copyImg.value = []//清空图片列表
  getIndex(sendTime.value, freightStatus.value, SelectCountry.value, pageNum.value, pageSize.value)
}

// 编辑物流弹窗
const editDialog = ref(false)
const editWay = ref()
//'国内快递','自提','指定代理','SHIP','AIR','俄罗斯双清关','EMS','TNT','FEDEX','UPS','DHL加急','DHL'
const waySelect = [
  {
    name: '国内快递',
    value: '国内快递'
  },
  {
    name: '自提',
    value: '自提'
  },
  {
    name: '指定代理',
    value: '指定代理'
  },
  {
    name: 'SHIP',
    value: 'SHIP'
  },
  {
    name: 'AIR',
    value: 'AIR'
  },
  {
    name: '俄罗斯双清关',
    value: '俄罗斯双清关'
  },
  {
    name: 'EMS',
    value: 'EMS'
  },
  {
    name: 'TNT',
    value: 'TNT'
  },
  {
    name: 'FEDEX',
    value: 'FEDEX'
  },
  {
    name: 'UPS',
    value: 'UPS'
  },
  {
    name: 'DHL加急',
    value: 'DHL加急'
  },
  {
    name: 'DHL',
    value: 'DHL'
  }
]
const editFee = ref()
const editDoc = ref()
const editAWB = ref()
const editId = ref()
const copyeEditItem = ref()
const edit = (id) => {
  console.log(id)
  copyeEditItem.value = id
  editWay.value = id.shipping_way
  editFee.value = id.Shipping_cost
  editDoc.value = id.OddNumbers
  editAWB.value = id.TransferNo
  editId.value = id.Shiptask_id
  editDialog.value = true
}
const isDisabled = ref(true)
const transportEdit = () => {
  api.$transportEdit({
    token: token,
    shiptaskid: editId.value,
    way: editWay.value,
    fee: editFee.value,
    delivery: editDoc.value,
    turn_delivery: editAWB.value
  }).then(res => {
    // activeIndex.value = editId.value
    console.log(isDisabled.value)
    ElMessage({
      type: 'success',
      message: "Edit succeeded!"
    })
    editDialog.value = false
    editWay.value = ''
    editFee.value = ''
    editDoc.value = ''
    editAWB.value = ''
  }).catch(err => {
    console.log(err)
  })
}
watch([editWay, editFee, editDoc, editAWB], (newValue, oldValue) => {
  if (newValue[0] == null || newValue[1] == null || newValue[2] == null) {
    isDisabled.value = true
  } else if (newValue[0] != copyeEditItem.value.shipping_way || newValue[1] != copyeEditItem.value.Shipping_cost || newValue[2] != copyeEditItem.value.OddNumbers || newValue[3] != copyeEditItem.value.TransferNo) {
    isDisabled.value = false
  }
})

//保存编辑
const editSave = () => {
  transportEdit()
  getIndex(sendTime.value, freightStatus.value, SelectCountry.value, pageNum.value, pageSize.value)
}
//取消编辑
const cancelEdit = () => {
  editDialog.value = false
  editWay.value = ''
  editFee.value = ''
  editDoc.value = ''
  editAWB.value = ''
}

onMounted(() => {
  //首页加载
  getIndex(sendTime.value, freightStatus.value, SelectCountry.value, pageNum.value, pageSize.value)
  getFreightStatus()
  getTime()
})

onUpdated(() => {
  renderColor()
  isDisabled.value = true
})
</script>
<style lang="less" scoped>
@import "./css/shipment.less";
</style>